package iNotes;

import iNotes.assist.DataPool;
import iNotes.assist.Utils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;

@WebServlet(name = "ShareItem", value = "/ShareItem")
public class ShareItem extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        return;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        if(!Utils.checkToken(session,request)){
            response.getWriter().write("CSRF attack detected!");
            return;
        }
        String target = request.getParameter("target");
        int noteID = Integer.parseInt(request.getParameter("noteid"));
        int uid = (int) session.getAttribute("uid");

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        CallableStatement callableStatement = null;
        try {
            connection = DataPool.ds.getConnection();
            if (Utils.checkBelonging(connection, uid, noteID)) {
                callableStatement = connection.prepareCall("{call checkExist(?,?)}");
                callableStatement.setString(1, target);
                callableStatement.registerOutParameter(2, Types.INTEGER);
                callableStatement.execute();
                int id = callableStatement.getInt(2);
                if (id == 0) {
                    session.setAttribute("targetNotFound", target);
                } else {
                    preparedStatement = connection.prepareStatement("insert into note_share values(?,?,?);");
                    preparedStatement.setInt(1, uid);
                    preparedStatement.setInt(2, id);
                    preparedStatement.setInt(3, noteID);
                    preparedStatement.execute();
                    session.setAttribute("shareTarget", target);
                }
            }
        } catch (SQLException throwables) {
            if (throwables.getClass() == SQLIntegrityConstraintViolationException.class) {
                System.err.println("User shared same notes.");
                session.setAttribute("duplicatedShare", "true");
            } else {
                throwables.printStackTrace();
            }
        } finally {
            Utils.close(connection,null,callableStatement,preparedStatement);
        }
        response.sendRedirect("notes.jsp");
    }
}
